// pages/settings/settings.js
const util = require("../../utils/util");
const majors = {
  "保密":['保密'],
  "经济学": ["国际经济与贸易", "金融工程", "数字经济"],
  "法学": ["法学", "知识产权"],
  "教育学": ["学前教育", "教育技术学", "体育教育", "社会体育指导与管理", "应用心理学"],
  "文学": ["汉语言文学", "汉语国际教育", "英语", "日语", "商务英语", "网络与新媒体"],
  "理学": [
    "数学与应用数学", "物理学", "应用物理学", "化学", "应用化学", 
    "地理科学", "地理信息科学", "生物科学", "统计学"
  ],
  "工学": [
    "机械设计制造及其自动化", "车辆工程", "智能制造工程", "材料成型及控制工程",
    "焊接技术与工程", "复合材料与工程", "电子信息工程", "微电子科学与工程",
    "人工智能", "自动化", "计算机科学与技术", "软件工程", "网络工程",
    "物联网工程", "数据科学与大数据技术", "土木工程", "化学工程与工艺",
    "环境工程", "环境生态工程", "资源环境科学", "食品质量与安全",
    "城乡规划", "建筑学", "风景园林", "工程造价"
  ],
  "医学": [
    "临床医学", "口腔医学", "预防医学", "护理学", "药学", "生物制药",
    "医学检验技术", "康复治疗学"
  ],
  "管理学": [
    "会计学", "审计学", "工商管理", "市场营销", "物流管理", "旅游管理",
    "酒店管理", "跨境电子商务"
  ],
  "艺术学": [
    "音乐学", "舞蹈学", "美术学", "绘画", "视觉传达设计", "环境设计", "产品设计"
  ]
};
Page({
  /**
   * 页面的初始数据
   */
  data: {
    majorData : {
      "保密":['保密'],
      "经济学": ["国际经济与贸易", "金融工程", "数字经济"],
      "法学": ["法学", "知识产权"],
      "教育学": ["学前教育", "教育技术学", "体育教育", "社会体育指导与管理", "应用心理学"],
      "文学": ["汉语言文学", "汉语国际教育", "英语", "日语", "商务英语", "网络与新媒体"],
      "理学": [
        "数学与应用数学", "物理学", "应用物理学", "化学", "应用化学", 
        "地理科学", "地理信息科学", "生物科学", "统计学"
      ],
      "工学": [
        "机械设计制造及其自动化", "车辆工程", "智能制造工程", "材料成型及控制工程",
        "焊接技术与工程", "复合材料与工程", "电子信息工程", "微电子科学与工程",
        "人工智能", "自动化", "计算机科学与技术", "软件工程", "网络工程",
        "物联网工程", "数据科学与大数据技术", "土木工程", "化学工程与工艺",
        "环境工程", "环境生态工程", "资源环境科学", "食品质量与安全",
        "城乡规划", "建筑学", "风景园林", "工程造价"
      ],
      "医学": [
        "临床医学", "口腔医学", "预防医学", "护理学", "药学", "生物制药",
        "医学检验技术", "康复治疗学"
      ],
      "管理学": [
        "会计学", "审计学", "工商管理", "市场营销", "物流管理", "旅游管理",
        "酒店管理", "跨境电子商务"
      ],
      "艺术学": [
        "音乐学", "舞蹈学", "美术学", "绘画", "视觉传达设计", "环境设计", "产品设计"
      ]
    },
    sexShow: false,
    sex:'保密',
    majorShow:false,
    category:'保密',
    nickname:null,
    student_id:null,
    grade:2020,
    gradeIndex:null,
    major:null,
    username:null,
    majorname:null,
    actions: [
      {name: '男'},
      {name: '女'}, 
      {name: '保密'}, 
    ],
    columns:null,
     // 新增数据项
    gradeShow: false,
    gradeColumns: []  // 年份数据存储
  },

  onClickLeft(event){
    wx.switchTab({
      url: '/pages/me/me',
    })
  },

  onClose() {
    this.setData({ sexShow: false });
  },

  onSelect(event) {
    let csex = event.detail.name;
    this.setData({
      sex:csex
    });
    console.log(event.detail);
  },

  closeMajor(event){
    this.setData({ majorShow: false });
  },

  changeSex(event){
      this.setData({ sexShow: true });
  },

  changeMajor(event){
    this.setData({ majorShow: true });
  },

  majorConfirm(event) {
    // 获取所有列的选中值数组（适用于多列联动）
    const selectedValues = event.detail.value; 
    // 获取所有列的索引数组（核心需要的内容）
    const columnIndexes = event.detail.index; 
    
    // 示例：获取第一列索引
    const firstColumnIndex = columnIndexes[0];
    // 示例：获取第二列索引
    const secondColumnIndex = columnIndexes[1];
    
    console.log('所有列索引:', columnIndexes);
    this.setData({
      majorShow: false,
      category:firstColumnIndex,
      major:secondColumnIndex,
      majorname:majors[Object.keys(majors)[firstColumnIndex]][secondColumnIndex]
    });
  },

  majorChange(event) {
    const { picker, value, index } = event.detail;
    picker.setColumnValues(1, majors[value[0]]);
    console.log(value[1],"  ",majors[value[0]]);
    let optionIndex = picker.getColumnIndex(1);
    console.log(optionIndex);
  },

    // 新增方法集
  changeGrade() {
    this.setData({ gradeShow: true });
  },

  closeGrade() {
    this.setData({ gradeShow: false });
  },

  gradeConfirm(event) {
    const selectedYear = event.detail.value.text;
    this.setData({
      grade: selectedYear,
      gradeShow: false
    });
    wx.setStorageSync('grade', selectedYear); // 持久化存储
  },

  toUpdate(e){
    const values = e.detail.value;
    let nname = values.nickname;
    let sid = values.student_id;
    let uid = wx.getStorageSync('uid');

    wx.request({
      url: 'http://127.0.0.1:3527/users/update',
      method:'PUT',
      data:{
        "category":this.data.category,
        "major":this.data.major,
        "nickname":nname,
        "student_id":sid,
        "sex":this.data.sex,
        "grade":this.data.grade,
        "user_id":uid
      },
      success: (res) => {
        if (res.data.code === 200) {
          util.showSuccessToast("修改成功");
          console.log(res);
          try {
            wx.setStorageSync('category', this.data.category);
            wx.setStorageSync('major', this.data.major);
            wx.setStorageSync('nickname', nname);
            wx.setStorageSync('student_id', sid);
            wx.setStorageSync('sex', this.data.sex);
            wx.setStorageSync('grade', this.data.grade);
          } catch (e) {
            console.log("存储失败");
           }
        }else {
          util.showErrorToast('修改失败')
        };
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let uid = wx.getStorageSync('uid');
    if (!uid) wx.switchTab({
      url: '/pages/me/me',
    });
    this.setData({
      username : wx.getStorageSync('username'),
      grade : wx.getStorageSync('grade'),
      nickname : wx.getStorageSync('nickname'),
      student_id : wx.getStorageSync('student_id'),
      major:wx.getStorageSync('major'),
      sex:wx.getStorageSync('sex'),
      category:wx.getStorageSync('category'), 
    });
    let mn = majors[Object.keys(majors)[this.data.category]][this.data.major];
    this.setData({
      majorname:mn,
      columns:[
        {
          values: Object.keys(majors),
          className: 'column1',
          defaultIndex:this.data.category,
        },
        {
          values: majors[Object.keys(majors)[this.data.category]],
          className: 'column2',
          defaultIndex:this.data.major
        },
      ]
    });

     // 生成年份数组（1949-当前年）
    const currentYear = new Date().getFullYear();
    const years = [];
    for (let i = 1949; i <= currentYear; i++) {
      years.push({ text: i.toString() }); // 必须对象格式[8](@ref)
    }
    this.setData({
      gradeColumns: years,
      grade: wx.getStorageSync('grade') || currentYear // 默认当前年
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const currentYear = new Date().getFullYear();
    let defaultIndex = this.data.gradeColumns.findIndex(item => 
      item.text === this.data.grade.toString()
    );
    defaultIndex = defaultIndex !== -1 ? defaultIndex : currentYear - 1949;
    this.setData({
      gradeIndex:defaultIndex
    });
  },

  logout(event){
    try {
      wx.clearStorageSync();
      wx.reLaunch({
        url: '/pages/me/me',
      })
    } catch (e) {
      console.error('退出登录失败', e)
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let uid = wx.getStorageSync('uid');
    if (!uid) wx.switchTab({
      url: '/pages/me/me',
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})